<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 500px;
        height: 300px;
        border: 1px solid #000;
        display: flex;
        justify-content: space-between;
      }
      .left {
        width: 200px;
        height: 300px;
        background-color: rgb(245, 167, 167);
      }
      .right {
        width: 200px;
        height: 300px;
        background-color: rgb(252, 208, 152);
      }

      p {
        margin: 0;
        padding: 0;
        background-color: rgb(154, 202, 254);
        height: 30px;
        margin-bottom: 5px;
        text-align: center;
        line-height: 30px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <div class="left">
        <p draggable="true" id="p1">1</p>
        <p draggable="true" id="p2">2</p>
        <p draggable="true" id="p3">3</p>
        <p draggable="true" id="p4">4</p>
      </div>
      <div class="right">
        <p draggable="true" id="p5">5</p>
        <p draggable="true" id="p6">6</p>
        <p draggable="true" id="p7">7</p>
      </div>
    </div>

    <script>
      // appendChild 方法的设计是为了确保一个节点在 DOM 树中只能有一个父节点。
      // 当你将一个节点从一个父节点移动到另一个父节点时，原父节点会自动将其子节点删除，
      // 从而保持节点的唯一性。这种行为确保了 DOM 结构的完整性和一致性。
      let left = document.querySelector(".left");
      let right = document.querySelector(".right");
      function dragP(x, y) {
        x.addEventListener("dragstart", function (e) {
          e.dataTransfer.setData("text/plain", e.target.id);
        });
        y.addEventListener("dragover", function (e) {
          e.preventDefault();
        });
        y.addEventListener("drop", function (e) {
          let id = e.dataTransfer.getData("text/plain");
          let p = document.getElementById(id);
          y.appendChild(p);
        });
      }

      dragP(right, left);
      dragP(left, right);
    </script>
  </body>
</html>
